package com.superatom.designpattern.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 动态代理Star
 */
public class DynamicStarHandler implements InvocationHandler {
    private Star star;

    public DynamicStarHandler(Star star){
        this.star = star;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object object = null;
        System.out.println("订票");
        if(method.getName().equals("sing")){
            // 调用返回值
            object = method.invoke(star,args);
        }
        System.out.println("收钱");
        return object;
    }

    public Star getProxy(DynamicStarHandler handler){
        Class clazz = Star.class;
        return  (Star) Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), handler);
    }

    public static void main(String[] args) {
        DynamicStarHandler handler = new DynamicStarHandler(new RealStar());

        Star proxy = handler.getProxy(handler);
        proxy.sign();
        proxy.sing();

    }
}
